<?php

namespace App\Http\Middleware\User;

use Closure;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class UserMiddleware extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try{
            if (!$this -> auth -> parser() -> setRequest($request) -> hasToken()) {
                throw new \Exception('token不能为空');
            }

            if (!Auth::guard('user_api') -> check()) {
                return response() -> json([
                    'error_code' => 401,
                    'msg' => 'token无效或已过期'
                ]);
                //throw new \Exception('token无效或已过期');
            }

            return $next($request);

        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }

    }
}
